<?php
   namespace app\admin\controller;
   use \think\Cookie;
   class Sp extends \think\Controller{
	   public $mec;
	   function __construct(){

  		parent::__construct();
      $this->mec=new \app\admin\controller\Memcache();
  	}
      function index($page=1){
	    $new=new \app\index\controller\Fy($page);
      	$spcont=$new->data('sp',5);//data(表名,每页显示的页数);
	    $sp=\think\Db::name('sp')->limit($spcont['limit'],$spcont['num'])->select();
		foreach($sp as $v){
		   $spid[]=$v['id'];
		}

		$img=\think\Db::name('img_list')->where('sp_id in ('.join(',',$spid).')')->select();
		   $stand=\think\Db::name('stand_list')->field('stand_name,sp_id')->where('stand_cid=0 and sp_id in ('.join(',',$spid).')')->group('sp_id')->select();
           $sp_=[];
           $fl=[];
           $img_list=[];
           $stand_=[];
		   foreach($this->mec->mem->get('fl') as $v){
		   	    $list=explode('-',$v['fl_name']);
                $fl[$v['id']]=$list[count($list)-1];
		   }
		   foreach($img as $v){
		   	  $list=explode(',',$v['img_list']);
		   	  $img_list[$v['sp_id']]=$list[0];
		   }
          
          foreach($stand as $v){
          	$frist=explode('-',$v['stand_name']);
          	$mony=explode(',',$frist[0]);
          	$ku=explode(',',$frist[1]);
          	$stand_[$v['sp_id']]['mony']=$mony[0];
          	$stand_[$v['sp_id']]['ku']=$ku[0];
          }

	    $fy=$new->list_page($new,'/sp/index',$spcont['count'],['上一页','下一页'],'class,class_','page_a,a_page');//list_page(对象,url,总页数,['上一页的文字','下一页的文字'],上下页激活按钮class名/禁止点击class名,页码选中class名/没选中class名);

		   $this->assign(['sp'=>$sp,'fl'=>$fl,'img'=>$img_list,'brand'=>$this->mec->mem->get('brand'),'stand'=>$stand_,'fy'=>$fy]);
	     return $this->fetch('index/sp_data');
	  }


//推荐明星商品/取消明星商品
	function sp_starsp(){
	     $p=input('post.');
		 if(intval($p['starsp'])==0){
		     $p['starsp']=1;
		 }else{
		    $p['starsp']=0;
		 }
		 $starsp=\think\Db::name('sp')->where('id',$p['id'])->update(['sp_starsp'=>$p['starsp']]);
		 if($starsp){
		    echo JSON_encode(['status'=>'ok','starsp'=>$p['starsp']]);
		 }else{
		   echo JSON_encode(['status'=>'fail']);
		 }
	}



	 function icon(){
           if(!$_FILES['file']['error']){
            $fg=explode('.',$_FILES['file']['name']);
            $cont=count($fg);
            $filename='upload_time/'.time().'.'.$fg[$cont-1];
            $filename_=explode('/',$filename);
            if(move_uploaded_file($_FILES['file']['tmp_name'],$filename)){

            	echo JSON_encode(['status'=>'ok','file_url'=>$filename]);
            }else{
              echo JSON_encode(['status'=>'faile']);
           }  
        }
	 }

	  function sp_add($id=''){
	      if($id){
	      	  $sp=\think\Db::name('sp')->find($id);
	      	  $img=\think\Db::name('img_list')->field('img_list')->where('sp_id',$sp['id'])->find();
	      	  $details=\think\Db::name('details')->field('content')->where('sp_id',$sp['id'])->find();
	      	  $img_=explode(",",$img['img_list']);
	      	  $this->assign(['sp'=>$sp,'img'=>$img_,'details'=>$details['content']]);
	      }

	      	if(!$brand=$this->mec->mem->get('brand')){
               $brand=\think\Db::name('brand')->select();
               $this->mec->mem->set('brand',$brand);
  	 	  }
	      $this->assign(['fl'=>$this->mec->mem->get('fl'),'brand'=>$brand]);
	     return $this->fetch('index/sp_add');
	  }

    function stand_list(){
    	if(Cookie::has('stand_time')){
    		 $this->assign('stand_time',Cookie::get('stand_time'));
    	}
      $this->assign('list',$this->mec->mem->get('stand'));
       return $this->fetch('index/stand_list');
    }


//删除商品
function sp_del(){
   if(intval(input('post.id'))){
	   \think\Db::startTrans();
       $sp_del=\think\Db::name('sp')->delete(input('post.id'));
	   if(!$sp_del){\think\Db::rollback();echo JSON_encode(['status'=>'fail']);}
	   $img_del=\think\Db::name('img_list')->where(['sp_id'=>input('post.id')])->delete();
	   if(!$img_del){\think\Db::rollback();echo JSON_encode(['status'=>'fail']);}
	   $stand_del=\think\Db::name('stand_list')->where(['sp_id'=>input('post.id')])->delete();    
	   if($stand_del){
	       \think\Db::commit();
		   echo JSON_encode(['status'=>'ok']);
	   }else{
	       \think\Db::rollback();
		   echo JSON_encode(['status'=>'fail']);
	    }
   }
}

//添加商品
   function spall_insert($id=0){
   	 $post=input('post.');
   	         \think\Db::startTrans();
      $img=[];
      if($id){
      	$sp=\think\Db::name('sp')->where('id',$id)->update($post['sp']);
      }else{
      	$sp=\think\Db::name('sp')->insertgetId($post['sp']);
      }
      if($sp){
      	 foreach($post['img_list'] as $v){

         if($v!='' and $id==0){
         	$file=explode('/',$v);
         	if(copy($file[count($file)-2]."/".$file[count($file)-1],"upload/".$file[count($file)-1])){
                    $img[]="/"."upload/".$file[count($file)-1];
            	}else{
            		\think\Db::rollback();
                     echo JSON_encode(['status'=>'faile']);
                     die();
            	}
         	 
         }else{
         	 $file=explode('/',$v);
         	 if($file['1']=='upload'){
         	 	$img[]=$v;
         	 }else{
         	 	if(copy($file[1].'/'.$file[2],"upload/".$file[count($file)-1])){
                   $img[]="/"."upload/".$file[count($file)-1];
         	 	}
         	 }
         }
      }
        if($id){
        	 $img=\think\Db::name('img_list')->where('sp_id',$id)->update(['img_list'=>join(',',$img),'sp_id'=>$id]);
        }else{
        	  $img=\think\Db::name('img_list')->insert(['img_list'=>join(',',$img),'sp_id'=>$sp]);
        }
    
     if($img){
        if($id){
     	    $details=\think\Db::name('details')->where('sp_id',$id)->update(['content'=>htmlspecialchars_decode($post['details']),'sp_id'=>$id]);
        }else{
        	$details=\think\Db::name('details')->insert(['content'=>htmlspecialchars_decode($post['details']),'sp_id'=>$sp]);
        }

     	if($details){
     		$mony=$post['mony'];
     		$ku=$post['ku'];
     		$res_monyku=[];
     		if($id){
     			 $del_stand=\think\Db::name('stand_list')->where('sp_id',$id)->delete();
     			 $sp=$id;
     		}
             $res_id=$this->stand_insert($post['stand_arr'],$sp);
     		
     		foreach($mony as $k=>$v){
     			$join=join(',',$v)."-".join(',',$ku[$k]);
     			$res_monyku[]=\think\Db::name('stand_list')->insert(['stand_name'=>$join,'stand_id'=>$res_id[$k],'stand_cid'=>0,'sp_id'=>$sp,'stand_num'=>1]);
     		}
     		if(in_array('false',$res_monyku)){
     			 \think\Db::rollback();
     			 echo JSON_encode(['status'=>'fail']); 
     		}else{
     			\think\Db::commit();
     			echo JSON_encode(['status'=>'ok']);
     		}
        
    }else{
    	\think\Db::rollback();
    	echo JSON_encode(['status'=>'fail']); 
    }
     	
    }
      
     }else{
     	\think\Db::rollback();
     	echo JSON_encode(['status'=>'fail']);
     }

      
   }


function stand_insert($_arr=[],$sp_id=''){
      $id=[];
       $num=0;
       $ma=1;
       $lr=0;
       $i_=0;
       $id_=[];
       $key_id=0;
       $stand_id=[];
       foreach($_arr as $k=>$v){
       	foreach($v as $kk=>$vv){
       	    if(is_array($vv)){
       	    	    $cid=[];
                if($ma==1 and count($vv)==1){
                	$ma_time=2;
                }else{
                	$ma_time=count($vv);
                }
       	         for($a_=0;$a_<($ma==1?$ma_time:$ma);$a_++){
       	        	 if($num==1){
                       $id_r=$id[$i_];
                       if($i_==(count($id)-1)){
                       	   $i_=0; 
                       }else{
                       	   $i_++;
                       }

                        foreach($vv as $k_=>$v_){
                         if(isset($stand_id['id']) and $kk==$stand_id['id']){
                         	  $cid[]=\think\Db::name('stand_list')->insertgetId(['stand_name'=>$v_,'stand_id'=>$id_r,'stand_cid'=>$kk,'sp_id'=>$sp_id,'stand_num'=>$k_+1]);

                         }else{

                           $cid[$k_]=\think\Db::name('stand_list')->insertgetId(['stand_name'=>$v_,'stand_id'=>$id_r,'stand_cid'=>$kk,'sp_id'=>$sp_id,'stand_num'=>$k_+1]);
                       }
                    
                           $stand_id['id']=$kk;
                        }       
                       
       	        	 }else{
       	        	 	
     
       	        	 	if(count($vv)==1){
       	        	 	   $cid[$a_]=\think\Db::name('stand_list')->insertgetId(['stand_name'=>$vv[$a_],'stand_id'=>isset($id[0])?$id[0]:0,'stand_cid'=>$kk,'sp_id'=>$sp_id,'stand_num'=>$a_+1]);
       	        	 	   break;
       	        	 	}else{
       	        	 		$cid[$a_]=\think\Db::name('stand_list')->insertgetId(['stand_name'=>$vv[$a_],'stand_id'=>isset($id[0])?$id[0]:0,'stand_cid'=>$kk,'sp_id'=>$sp_id,'stand_num'=>$a_+1]);
       	        	 	}

       	        	 }
       	        	
                  

       	        }
       	            $ma=$ma*count($vv);

       	                 
       	            $id=$cid;
       	            if(count($vv)>=2){
       	             $num=1;
       	            }else{
       	            	$num=0;
       	            }

       	        
       	    }else{
       	    	$id[0]=\think\Db::name('stand_list')->insertgetId(['stand_name'=>$vv,'stand_id'=>isset($id[0])?$id[0]:0,'stand_cid'=>$kk,'sp_id'=>$sp_id,'stand_num'=>1]);
       	    	if($key_id==0){
       	    		$id_[]=$id[0];
       	    		$key_id=1;
       	    	}
       	    }
       	  }
       	  $id=[];
       	  $key_id=0;
       	  $ma=1;      
       	  $num=0;
       	  $stand_id=[];
       	  $i_=0;
       	  $lr=0;

     }
     return $id_;

}



    function stand_list_save(){

    	/*

array(4) {
  [1]=>
  array(1) {
    [0]=>
    string(6) "蓝色"
  }
  [2]=>
  array(1) {
    [0]=>
    string(2) "xl"
  }
  [3]=>
  array(2) {
    [0]=>
    string(3) "10G"
    [1]=>
    string(3) "20G"
  }
  [5]=>
  array(2) {
    [0]=>
    string(2) "35"
    [1]=>
    string(2) "36"
  }
}
    
    	 */
    if(input('post.id')){
        $arr=[];//表格数据
        $arr_time=[];
        $key=[];//规格id
        $mony_ku=[];
        $mk_k=0;
        $res=\think\Db::name('stand_list')->where('sp_id',input('post.id'))->select();
        foreach($res as $k=>$v){
        	 if($v['stand_cid']!=0 and !in_array($v['stand_cid'],$key)){
        	 	 $key[]=$v['stand_cid'];
        	 }
        	 if($v['stand_cid']!=0 and !in_array($v['stand_name'],$arr_time)){
        	 	    $arr_time[]=$v['stand_name'];

                    $arr[$v['stand_cid']][]=$v['stand_name'];
        	 }
        	 if($v['stand_cid']==0){
        	 	$mony_ku_=explode('-',$v['stand_name']);
               $mony_ku[$mk_k]['mony']=explode(',',$mony_ku_[0]);
               $mony_ku[$mk_k]['ku']=explode(',',$mony_ku_[1]);
               $mk_k++;
        	 } 
        	}

    }else{
      $post=input('post.');
      $list=$post['list'];
      $key=[];
      $stand=$this->mec->mem->get('stand');
       foreach($list as $v){
          $str=explode(',',$v);
          $arr[$str[0]][]=$str[1];
          if(!in_array($str[0],$key)){
            $key[]=$str[0];
          }
          
       }
    }
  
       Cookie::set('stand_time',$arr);
       ksort($arr);

       sort($key);
       $res=\think\Db::name('stand')->field('id,stand_name')->where('id in ('.join(',',$key).')')->select();
       $th='<tr>';
       foreach($res as $v){
        $th.='<th class="bgtt" v-for="v in table_title">'.$v['stand_name'].'<input type="hidden" name="rule_id[]" value="'.$v['id'].'"><input type="hidden" name="rule_name[]" value="'.$v['stand_name'].'"></th>';
       }

        			
					
	    $th.='<th class="bgtt">价格(元)</th><th class="bgtt">库存(件)</th>';
		$th.='</tr>';		
       $i=0;
       $max=1;
       $_arr=[];
       $str="";
		$aa=0;
		$str.="<table  style='width:620px;'' cellspacing='0' class='list'>";
		$str.=$th;
		foreach($arr[$key[0]] as $k=>$v){

			   if($aa==0){
			   	$_arr[$k][$key[0]]=$v;
			         $aa=$key[0];	
			   	    unset($key[0]);
			   	   
			  }else{
			  	$_arr[$k][$aa]=$v;
			  }
			
			$str.='<tr align="center"><td class="td">'.$v.'</td>';
			foreach($key as $kk=>$kv){
              if(array_key_exists($kv, $arr)){//array_key_exitst(key,array) 判断array数组中是否存在key键名

               	  $_arr[$k][$kv]=$arr[$kv];

              	
              	 $str.="<td class='td'><table  width='100%' height='100%' cellspacing='0' class='list_'>";
              	if(count($arr[$kv])>$max and $i==0){
                  $max=count($arr[$kv]);
              	    $i++;
                      foreach($arr[$kv] as $_a){
              	    		$str.="<tr><td>".$_a."</td></tr>";
                 	}
                 }else{
                 	//echo $max;
                 	$max_=0;
              	    for($b=0;$b<=$max-1;$b++){
              	    	  foreach($arr[$kv] as $_a){ 
              	    	  	$max_++;
              	    	    	$str.="<tr><td>".$_a."</td></tr>";
              	    	 } 
                 	 }  
                 	
                   
                 $max=$max_;
              }
              $str.="</table></td>";
            }
           }
         
           $str.='<td class="td" align="center"><table  width="100%" height="100%" cellspacing="0" class="list_ stand_mony">';
           for($inp=1;$inp<=$max;$inp++){
           	$val=isset($mony_ku[$k]['mony'][$inp-1])?$mony_ku[$k]['mony'][$inp-1]:'';
               $str.='<tr  align="center" ><td align="center"><input type="number" style="width:50px;display:block;" value="'."{$val}".'" /></td></tr>';   	   
           }
           $str.='</table></td>';

           $str.='<td class="td" align="center"><table  width="100%" height="100%" cellspacing="0" class="list_ ku">';
           for($inp=1;$inp<=$max;$inp++){
           	$val=isset($mony_ku[$k]['ku'][$inp-1])?$mony_ku[$k]['ku'][$inp-1]:'';
               $str.='<tr  align="center"><td align="center"><input type="number" style="width:50px;display:block;" value="'."{$val}".'" /></td></tr>';   	   
           }
           $str.='</table></td>';
           $i=0;
           if(count($arr[$aa])-1!=$k){
             $max=1;
           }
           

       }
       $str.="</table>";
       //添加
       //echo '<pre/>';
      //var_dump($_arr[0]);

     /*  $id=[];
       $num=0;
       $ma=1;
       $lr=0;
       $i_=0;
       $stand_id=[];
       foreach($_arr as $k=>$v){
       	foreach($v as $kk=>$vv){
       	    if(is_array($vv)){
       	    	    $cid=[];
       	         for($a_=0;$a_<($ma==1?2:$ma);$a_++){
       	        	 if($num==1){
                       
                       $id_r=$id[$i_];
                       if($i_==(count($id)-1)){
                       	   $i_=0; 
                       }else{
                       	   $i_++;
                       }
                       echo "okokok";
                   
                        foreach($vv as $k_=>$v_){
                         if(isset($stand_id['id']) and $kk==$stand_id['id']){
                         	  $cid[]=\think\Db::name('stand_list_copy')->insertgetId(['stand_name'=>$v_,'stand_id'=>$id_r,'stand_cid'=>$kk,'sp_id'=>2,'stand_num'=>$k_+1]);

                         }else{
                           $cid[$k_]=\think\Db::name('stand_list_copy')->insertgetId(['stand_name'=>$v_,'stand_id'=>$id_r,'stand_cid'=>$kk,'sp_id'=>2,'stand_num'=>$k_+1]);
                       }
                    
                           $stand_id['id']=$kk;
                        }       
                       
                       
       	        	 }else{
       	        	 	 $cid[$a_]=\think\Db::name('stand_list_copy')->insertgetId(['stand_name'=>$vv[$a_],'stand_id'=>isset($id[0])?$id[0]:0,'stand_cid'=>$kk,'sp_id'=>2,'stand_num'=>$a_+1]);
       	        	 }
       	        	
                  

       	        }
       	     
       	            $ma=$ma*count($vv);      
       	            $id=$cid;
       	             $num=1;

       	        
       	    }else{
       	    	$id[0]=\think\Db::name('stand_list_copy')->insertgetId(['stand_name'=>$vv,'stand_id'=>isset($id[0])?$id[0]:0,'stand_cid'=>$kk,'sp_id'=>2,'stand_num'=>1]);
       	    }
       	  }
       	  $id=[];
       	  $ma=1;      
       	  $num=0;
     }
*/

       echo JSON_encode(['status'=>'ok','list'=>$str,'title'=>$res,'arr'=>$_arr]);
    }

    function clear_list(){
    	  Cookie::set('stand_time','');
    }

   }

?>
